package com.xqboss.web.core.config;

import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Maps;
import com.xqboss.common.enums.BaseEnum;
import com.xqboss.common.exception.ServiceException;
import com.xqboss.common.utils.StringUtils;
import org.springframework.core.convert.converter.Converter;

import java.util.Map;

/**
 * <p>
 * 枚举编码 -> 枚举 转化器
 * </p>
 * @author Trent
 * @date 2023/8/19
 */

public class StringToEnumConverter<T extends BaseEnum<Integer>> implements Converter<String, T> {
    private Map<Integer, T> enumMap = Maps.newHashMap();

    public StringToEnumConverter(Class<T> enumType) {
        T[] enums = enumType.getEnumConstants();
        for (T e : enums) {
            enumMap.put(e.getValue(), e);
        }
    }

    @Override
    public T convert(String source) {
        if(StringUtils.isEmpty(source)){
            return null;
        }
        int code;
        try{
            code = Integer.parseInt(source);
        }catch (Exception e){
            throw new ServiceException("类型参数错误");
        }
        T t = enumMap.get(code);
        if (ObjectUtil.isNull(t)) {
            throw new ServiceException("选择类型错误！！！");
        }
        return t;
    }
}